﻿using MovingChame.Web.Helpers;
using MovingChame.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MovingChame.Web.Infrastructure
{
    public class AlbumProvider : IAlbumProvider
    {
        private static AlbumProvider current;
        public static AlbumProvider Current
        {
            get
            {
                if (current == null) current = new AlbumProvider();
                return current;
            }
        }

        #region Configuration
        private string applicationName;
        public string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }

        private string connectionStringName;
        private string providerName;
        private MovingChameModelContainer db;

        public void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            providerName = name;

            if (config["applicationName"] != null)
                applicationName = config["applicationName"];

            if (config["connectionStringName"] != null)
            {
                connectionStringName = config["connectionStringName"];
                db = new MovingChameModelContainer();
                db.Database.Connection.ConnectionString = ConfigurationHelper.GetConnectionString(connectionStringName);
            }
            else
                db = new MovingChameModelContainer();
        }

        private AlbumProvider()
        {
            Initialize("AlbumProvider", new System.Collections.Specialized.NameValueCollection());
        }
        #endregion

        #region Interfact Methods

        public int AddPhotoToAlbum(int albumId, int photoId)
        {
            var newAlbumPhoto = new Album
            {
                AlbumId = albumId,
                PhotoId = photoId
            };
            db.Albums.Add(newAlbumPhoto);
            db.SaveChanges();
            return newAlbumPhoto.Id;
        }

        public bool RemovePhotoFromAlbum(int albumId, int photoId)
        {
            var removedPhoto = db.Albums.Where(o => o.AlbumId == albumId).SingleOrDefault(o => o.PhotoId == photoId);
            if (removedPhoto == null)
                return false;
            db.Albums.Remove(removedPhoto);
            db.SaveChanges();
            return true;
        }
        #endregion
    }
}